<template>
  <div class="Role" v-loading="loading">
    <el-card shadow="never">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="rolename" label="用户名">
          <el-input v-model="searchData.rolename" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" :disabled="!searchData.rolename && !searchData.phone"
            @click="handleSearch">
            查询
          </el-button>
          <el-button icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" style="margin-top: 10px;">
      <div class="card_button">
        <div>
          <el-button type="primary" icon="Plus" @click="handleEdit_Add">添加职位</el-button>
          <el-button type="danger" icon="Delete" @click="handleDeleteAll">批量删除</el-button>
        </div>
        <div>
          <el-button icon="Operation" circle plain />
          <el-button icon="Download" circle plain />
        </div>
      </div>
      <div class="card_table">
        <el-table :data="UserRoleList" @selection-change="selectchange" style="width: 100%" max-height="600px">
          <el-table-column width="100" align="center" type="selection" />
          <el-table-column label="序号" width="100" align="center" type="index" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="roleName" label="职位名" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip />
          <el-table-column fixed="right" min-width="240" label="操作" align="center">
            <template #default="scope">
              <el-button :loading="scope.row.loading" type="primary" text bg size="small"
                @click="handleRole(scope.row)">
                配置权限
              </el-button>
              <el-button type="primary" text bg size="small" @click="handleEdit_Add(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card_page">
        <el-Pagination :currentPage="paginationData.currentPage" :total="paginationData.total"
          :pageSize="paginationData.pageSize" :page-sizes="paginationData.pageSizes"
          :background="paginationData.background" :layout="paginationData.layout" @current-change="handleCurrentChange"
          @size-change="handleSizeChange"></el-Pagination>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑职位' : '添加职位'" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" label-position="left">
        <el-form-item prop="id" label="ID" v-if="formData.id">
          <el-input v-model="formData.id" disabled />
        </el-form-item>
        <el-form-item prop="roleName" label="职位名">
          <el-input v-model="formData.roleName" placeholder="请输入职位名..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm">
          取消
        </el-button>
        <el-button type="primary" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>


    <el-drawer v-model="drawer" title="分配职位权限">
      <el-tree style="max-width: 600px" :data="Roledata" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="SelectArry" :props="defaultProps" @check="currentChecked" />
      <template #footer>
        <el-button type="primary" @click="dearUpdate" :loading="Btnloading" :disabled="disableds">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="Role">
import { reactive, ref, watch } from 'vue';
import { AddRoleAPI, DeleteRoleAPI, EditRoleAPI, GetAllRoleAPI, RoleUserListAPI, SetRoleAPI } from '@/apis/acl/role/index'
import { usePagination } from '@/hooks/usePagination'


const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const loading = ref(false)
const btnloading = ref(false)
const Btnloading = ref(false)
const dialogVisible = ref(false)
const drawer = ref(false)

// 搜索框数据
const searchData = reactive({
  rolename: '',
  phone: ''
})

// 搜索
const handleSearch = () => {
  getRoleUserList()
}

// 重置
const resetSearch = () => {
  searchData.rolename = ''
  searchData.phone = ''
  getRoleUserList()
}

//#region 查
const UserRoleList = ref([])
const getRoleUserList = () => {
  loading.value = true
  RoleUserListAPI(
    paginationData.currentPage,
    paginationData.pageSize,
    searchData.rolename
  ).then((res) => {
    // console.log(res);
    UserRoleList.value = res.data.records.map((item: any) => {
      item.loading = false
      return item
    })
    paginationData.total = res.data.total
  }).catch(() => {
    ElMessage.error('加载失败请重试')
    UserRoleList.value = []
  }).finally(() => {
    loading.value = false
  })
}
//#endregion

//#region 增改
const formData = reactive({
  id: null,
  roleName: ''
})
const formRef = ref()
const formRules = reactive({
  roleName: [
    { required: true, message: '请输入用户名...', trigger: 'blur' },
    { min: 1, max: 8, message: '长度为1-8位', trigger: 'blur' },
  ]
})
const handleEdit_Add = (row: any) => {
  if (row) {
    formData.id = row.id
    formData.roleName = row.roleName
  }
  dialogVisible.value = true
}

// 提交
const handleCreateOrUpdate = () => {
  btnloading.value = true
  let api = formData.id ? EditRoleAPI : AddRoleAPI
  api(formData).then((res) => {
    // console.log(res); 编辑接口有问题201
    ElMessage.success(formData.id ? '编辑成功' : '添加成功')
    dialogVisible.value = false
    getRoleUserList()
  }).catch((error) => {
    ElMessage.error(error.message)
  }).finally(() => {
    btnloading.value = false
  })
}
//#endregion

//#region 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除:${row.roleName}吗?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    DeleteRoleAPI(row.id).then((res) => {
      // console.log(res);
      ElMessage.success('删除成功')
      getRoleUserList()
    })
  } catch (error) {
    ElMessage.error('已取消删除')
  }
}
// 批量删除
const handleDeleteAll = () => {
  console.log('批量删除删除');
}

// 表格多选
const selectchange = () => {
  console.log('11');
}
//#endregion

//#region 分配权限
const Roledata = ref([])  //所有权限
const SelectArry = ref([])  //选中权限
const ID = ref()  //点击为谁分配的id
const disableds = ref(true)
const handleRole = (row: any) => {
  row.loading = true
  ID.value = row.id
  GetAllRoleAPI(row.id).then((res) => {
    console.log(res.data);
    Roledata.value = res.data
    SelectArry.value = fillterSelectArr(Roledata.value, [])
    drawer.value = true
  }).catch(() => {
    ElMessage.error('请重试...')
  }).finally(() => {
    row.loading = false
  })
}
const fillterSelectArr = (allRole: any, ArryList: any) => {
  allRole.forEach((item: any) => {
    if (!item.children || item.children.length == 0) {
      if (item.select) {
        ArryList.push(item.id)
      }
    }
    if (item.children && item.children.length > 0) {
      fillterSelectArr(item.children, ArryList)
    }
  });
  return ArryList
}
const selectKeysArry = ref()
const currentChecked = (nodeObj: any, SelectedObj: any) => {
  disableds.value = false
  selectKeysArry.value = [...SelectedObj.checkedKeys, ...SelectedObj.halfCheckedKeys]
  // console.log('这是选中的节点的key数组',SelectedObj.checkedKeys)   // 这是选中的节点的key数组
  // console.log('这是选中的节点数组',SelectedObj.halfCheckedKeys)  // 这是半选的节点数组
}

// 确认按钮
const dearUpdate = () => {
  // console.log(SelectArry.value);
  Btnloading.value = true
  SetRoleAPI(ID.value, selectKeysArry.value).then((res: any) => {
    // console.log(res);
    drawer.value=false
    ElMessage.success('分配权限' + res.message)
    getRoleUserList()
  }).catch(()=>{
      ElMessage.error('失败请重试')
  }).finally(() => {
    Btnloading.value = false
    disableds.value = true
  })
  // console.log(selectKeysArry.value);
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
//#endregion


// 清空规则
const resetForm = () => {
  if (!formRef.value) return
  dialogVisible.value = false
  formRef.value.resetFields()
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getRoleUserList, { immediate: true })
</script>

<style scoped>
.Role {
  .card_button {
    display: flex;
    justify-content: space-between;
    align-content: center;
  }

  .card_page {
    display: flex;
    justify-content: space-around;
    align-content: center;
    margin-top: 10px;
  }
}
</style>
